package edu.msg.jthr.web.servlets;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.msg.jthr.backend.exception.ServiceException;
import edu.msg.jthr.backend.model.Candidate;
import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.service.CandidateService;
import edu.msg.jthr.backend.service.InterviewService;
import edu.msg.jthr.backend.service.UserService;
import edu.msg.jthr.web.util.RoleAssembler;

/**
 * @author Elod Servlet implementation for class UpdateCandidate
 */
@WebServlet("/UpdateCandidate")
public class UpdateCandidate extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private HttpSession session;
	@EJB
	private CandidateService candidateService;
	@EJB
	private InterviewService interviewService;
	@EJB
	private UserService userService;
	private static Logger LOG = LoggerFactory.getLogger(AddCandidate.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateCandidate() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		User user = (User) session.getAttribute("activeUser");
		if (user == null) {
			user = userService.getUserByUserName(request.getUserPrincipal()
					.toString());
			String role = RoleAssembler.getRole(user.getUserGroups());
			session.setAttribute("role", role);
			session.setAttribute("activeUser", user);
		}
		String pagePath = "/ShowJobs";
		request.getRequestDispatcher(pagePath).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		byte[] cv = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);

			for (FileItem item : items) {

				if (item.isFormField()) {
					String fieldname = item.getFieldName();
					String fieldvalue = item.getString();
					map.put(fieldname, fieldvalue);
				} else {
					item.getFieldName();
					FilenameUtils.getName(item.getName());
					item.getInputStream();
					cv = item.get();
					request.setAttribute("cv", cv);
				}
			}
		} catch (ServiceException | FileUploadException e) {
			LOG.error("Error by parseRequest!", e);
		}

		Candidate candidate = (Candidate) session.getAttribute("candidate");

		try {
			candidate.setFirstName((String) map.get("firstName"));
			candidate.setLastName((String) map.get("lastName"));
			candidate.setPhoneNumber((String) map.get("phoneNumber"));
			candidate.setMobileNumber((String) map.get("mobilNumber"));
			candidate.setMail((String) map.get("email"));
			candidate.setAddress((String) map.get("address"));
			candidate.setRelocation(Boolean.valueOf(map.get("relocation")));
			if (cv != null) {
				candidate.setCv(cv);
			}

			candidateService.update(candidate);
		} catch (ServiceException ex) {
			LOG.error("Getting error from the fields!", ex);
			System.out.println("Getting error from the fields!" + ex);
		}

		List<Candidate> candidateList = Collections.emptyList();

		try {
			candidateList = candidateService.getAll();
		} catch (ServiceException e) {
			LOG.error(e.getMessage());
		}

		session.setAttribute("candidateList", candidateList);
		request.getRequestDispatcher("/pages/ShowCandidates.jsp").forward(
				request, response);
	}

}
